var net = require('net');
var chatServer = net.createServer();
var clientList = [];
chatServer.on('connection', function(client) {

	console.log('get socket connection');
	client.name = client.remoteAddress + ':' + client.remotePort;
	clientList.push(client);
	client.write(client.name + ' welcome\n');

	// data
	client.on('data', function(chunk) {
		console.log(chunk);
		broadcast(chunk, client);
	});

	// end
	client.on('end', function() {
		console.log('end ' + client.name);
		var index = clientList.indexOf(client);
		clientList.splice(index, 1);
	});

	// error
	client.on('error', function(e) {
		console.log(e);
	});

});

function broadcast(message, client) {
	var cleanup = [];
	for (var i = 0; i < clientList.length; i++) {
		if (client != clientList[i]) {
			if (!client.writable) {
				cleanup.push(clientList[i]);
				clientList[i].destroy();
			} else {
				clientList[i].write(client.name + ' says ' + message);
			}
		}
	}

	//
	for (var i = 0; i < cleanup.length; i++) {
		var index = clientList.indexOf(cleanup[i]);
		clientList.splice(index, 1);
	}
}


chatServer.listen(9000);
console.log('start chat server ...');

// start
// node chp2-1.js
// in new cmd , type : telnet 127.0.0.1 9000